<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" clearable placeholder="标题" style="width: 200px;" class="filter-item" />


      <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="getList">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" >
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" width="500px;">
        <template slot-scope="{row}">
          <span>{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="200px">
        <template slot-scope="{row}">
          <!-- <span>{{ row.name }}</span> -->
          <img :src="baseimgurl + row.main_img" alt="" style="width:50px;height:50px;">
        </template>
      </el-table-column>
      <el-table-column label="视频" >
        <template slot-scope="{row}">
          <el-button v-if="row.video" size="mini" type="primary" @click="showvideo(row)">
            播放
          </el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="180px">
        <template slot-scope="{row}">
          <span>{{ row.ctime | formatDate }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ row.status | statusFilter }}
          </el-button> -->
          <el-button  size="mini" type="success" @click="resetdata(row)">
            编辑
          </el-button>

          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="dialogtitle" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title" />
        </el-form-item>

        <el-form-item label="视频">
            <el-upload
              ref="$upload"
              action=""
              class="video-uploader"
              :auto-upload="false"
              :on-change="onUploadvideo"
              accept="video/mp4, video/ogg, video/flv"
              >
              <el-button slot="trigger" size="small" type="primary">上传</el-button>
              <div slot="tip" class="el-upload__tip">
                <p v-if="!temp.video">video/mp4文件，且不能超过500MB</p>
                <video  v-if="temp.video" width="150" height="150" controls>
                  <source :src="baseimgurl+temp.video"  type="video/mp4">
                </video>
              </div>
            </el-upload>
        </el-form-item>

        <el-form-item label="资讯主图">
          <el-upload
            action=""
            accept="image/jpeg,image/png"
            :auto-upload="false"
            :on-change="onUploadxqimg"
            :show-file-list="false"
          >
            <el-button slot="trigger" size="small" type="primary">选取</el-button>
            <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button> -->
            <div slot="tip" class="el-upload__tip">
              <p v-if="!temp.main_img">只能上传jpg/png文件，且不能超过10m</p>
              <img v-if="temp.main_img" style="width:100px;border:1px solid green;height:100px;" :src="baseimgurl+temp.main_img" alt="">

            </div>

          </el-upload>
        </el-form-item>

        <el-form-item label="内容">

        </el-form-item>

        <div class="" style="width:700px;">
          <texteditor  v-model="temp.context" fileName="newsImg" />
        </div>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updataForm">
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="showdialogvideo">
      <video  width="800" height="500" controls>
        <source :src="baseimgurl+videourlshow"  type="video/mp4">
      </video>
    </el-dialog>
  </div>
</template>

<script>
const __ = {
  formatDate: (date, fmt) => {
    const padLeftZero = (str) => {
      return ('00' + str).substr(str.length)
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (const k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        const str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
    return fmt
  }
}
import { getnews , uploadVideo, storenes, deleteStorenews} from '@/api/store'
import { uploadImg } from '@/api/article'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import texteditor from '@/views/components/texteditor'
export default {
  name: 'ComplexTable',
  components: { Pagination, texteditor },
  filters: {
    formatDate(time) {
      return __.formatDate(new Date(time-0), 'yyyy-MM-dd hh:mm:ss')
    },
  },
  data() {

    return {
      videourlshow: '',
      showdialogvideo: false,
      baseimgurl: '',
      editorOption: {
        // some quill options
      },
      dialogtitle: '',
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 20,
        id:  undefined,
        title: undefined,
        sort: '+id'
      },
      listLoading: false,
      dialogFormVisible: false,
      temp: {
        main_img: '',
        title: '',
        video: '',
        context: '',
      },
      rules: {
        title: [{ required: true, message: '标题为必填项！', trigger: 'blur' }]
      },
    }


  },
  created() {
    this.getList();
  },
  methods: {

    handleDelete(row) {
      this.listLoading = true;
      this.$confirm(`确定要删除此资讯 ？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteStorenews({id: row.id}).then((res) => {
          console.log(res);
          this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })

      }).catch(() => {
        this.listLoading = false;
      });
      return false;
      deleteStore({ id: row.id, status: 0 }).then(() => {
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
      // this.list.splice(index, 1)
    },
    showvideo(data){
      console.log(data)
      this.showdialogvideo = true;
      this.videourlshow = data.video;
    },
    updataForm(){

      this.listLoading = true;
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          storenes(tempData).then(() => {
            this.dialogFormVisible = false;
            this.temp = {
              main_img: '',
              title: '',
              video: '',
              context: '',
            };
            this.$notify({
              title: 'Success',
              message: '更新成功！',
              type: 'success',
              duration: 2000
            });
            this.getList()
          })
        }else{
          this.listLoading = false;
        }
      })
      // console.log(this.temp)
    },
    onEditorBlur(quill) {
        console.log('editor blur!', quill)
      },
      onEditorFocus(quill) {
        console.log('editor focus!', quill)
      },
      onEditorReady(quill) {
        console.log('editor ready!', quill)
      },
    onUploadxqimg(file) {
      const _this = this
      const isIMAGE = (file.raw.type === 'image/jpeg' || file.raw.type === 'image/png');
      const isLt1M = file.size / 1024 / 1024 < 10;

      if (!isIMAGE) {
        this.$message.error('只能上传jpg/png图片!');
        return false;
      }
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 10MB!');
        return false;
      }


      var formFile = new FormData()
      formFile.append('file', file.raw)
      formFile.append('fileName', 'newsImg')
      this.isupload = true
      uploadImg(formFile).then(response => {
        // _this.temp.xqimg = 'http://localhost:8092/public'+response.data;
        _this.temp.main_img = response.fileUrl
      })
    },

    onUploadvideo(files) {
      const _this = this
      const file = files.raw
      console.log(file)
      const isVideo = file.type === 'video/mp4' || file.type === 'video/ogg' || file.type === 'video/flv';
      const isLt500MB = file.size / 1024 / 1024 < 500;

      if (!isVideo) {
        this.$message.error('请上传视频文件！');
      } else if (!isLt500MB) {
        this.$message.error('上传视频大小不能超过 500MB!');
      }
      var formFile = new FormData()
      formFile.append('file', file)
      formFile.append('fileName', 'newsvideo')
      this.isupload = true
      uploadVideo(formFile).then(response => {
        // _this.temp.xqimg = 'http://localhost:8092/public'+response.data;
        _this.temp.video = response.fileUrl
      })
      // this.pic_files = file;
      // var reader = new FileReader();
      // reader.readAsDataURL(file);
      // reader.onload = function(e){
      //   // console.log(e.target)
      //   _this.videourl = this.result;
      //     // console.log(this.result)//图片的base64数据
      // }
    },
    handleCreate() {
      // this.resetTemp()
      // this.$refs['$upload'].clearFiles();
      this.dialogtitle = '添加资讯'
      this.temp = {
        main_img: '',
        title: '',
        video: '',
        context: '',
      }
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.$refs['$upload'].clearFiles();
      })
    },
    resetdata(data){
      console.log(data);
      this.dialogtitle = '修改资讯'
      this.temp = data;
      this.dialogFormVisible = true
    },
    getList(){
      getnews(this.listQuery).then(response => {
        console.log(response)
        let list = response.data;
        // this.catypelist.forEach((el, idx) => {
        //   let data = response[idx] || {entry_fee: 0, proxy_fee: 0, user_fee:0};
        //   list.push({category_name: el.name, category_id: el.id, ...data})
        // })
        this.list = list;
        this.total = response.count
        this.listLoading = false
      })
    }
  }
}
</script>
